//
//  TalkViewController.swift
//  onemeetingmac
//
//  Created by 张衡 on 2020/7/1.
//  Copyright © 2020 onemeeting. All rights reserved.
//

import Foundation

class TalkViewController: NSViewController {
    var upMenu:NSMenu?
    
    var dataList:[ChatData]  {
        return Td.sh().chats
    }
    
    override func loadView() {
        let view = NSView.init(frame: NSMakeRect(0, 0, kTRTCUserWidth, kTRTCWinHeight))
        view.wantsLayer = true
        view.layer?.backgroundColor = NSColor.white.cgColor
        self.view = view
    }
    override func viewWillAppear() {
        super.viewWillAppear()
        //弹幕
        NotificationCenter.default.addObserver(self,selector: #selector(receiveBarrge(not:)),name:  MTReviBarrgeNotification,object: nil)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setupUI()
    }
    
    func setupUI() {
        self.view.layer?.backgroundColor = color_random_rgba().cgColor
        
        self.view.addSubview(barrageInput)
        barrageInput.snp.makeConstraints { (make) in
            make.bottom.centerX.width.equalToSuperview()
            make.height.equalTo(120)
        }
        
        
        self.view.addSubview(scrollView)
        scrollView.snp.makeConstraints { (make) in
            make.top.equalToSuperview()
            make.bottom.equalTo(barrageInput.snp.top)
            make.width.centerX.equalToSuperview()
        }
        
    }
    
    lazy var scrollView: NSScrollView = {
        let view = NSScrollView()
        view.documentView = self.tabView
        view.hasVerticalScroller = false
        view.hasHorizontalScroller = false
        view.autohidesScrollers = true
        view.drawsBackground = false
        view.wantsLayer = true
        view.layer?.backgroundColor = color_dark.cgColor
        return view
    }()
    
    
    lazy var tabView: NSTableView  = {
        let tab = NSTableView()
        tab.wantsLayer = true
        tab.backgroundColor = color_dark
        tab.delegate = self
        tab.dataSource = self

        tab.gridColor = color_dark
        tab.selectionHighlightStyle = .none

        let column = NSTableColumn.init(identifier: NSUserInterfaceItemIdentifier.init("column"))
        tab.addTableColumn(column)
        //column.width = self.view.frame.size.width
        tab.headerView = nil
        return tab
    }()
    
    lazy var barrageInput: TalkInputView = {
        let inp = TalkInputView.init(frame: NSRect.zero)
        inp.delegate = self
        inp.teView.txView.delegate = self
        return inp
    }()
    
    
    
}
extension TalkViewController:NSTextViewDelegate {
    func textDidChange(_ notification: Notification) {
        let textView = notification.object as? NSTextView
        let string = textView?.string ?? ""
        let emoji =  string.disable_emoji()
        if emoji.count > BARRAGE_MAX_LENGTH {
            textView?.string = emoji.substringk(toIndex: BARRAGE_MAX_LENGTH)
        }else {
            textView?.string = emoji
        }
    }
}

extension TalkViewController:NSTableViewDelegate,NSTableViewDataSource {
    func numberOfRows(in tableView: NSTableView) -> Int {
        return self.dataList.count
    }
    
    func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
        var cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier.init(mt_cell_default), owner: self) as? TalkCell
        let userInfo = self.dataList[row]
        if cell == nil {
            cell = TalkCell.init(info: userInfo,identifier: mt_cell_default)
        }
        return cell
    }
    
    func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
        let info = self.dataList[row]
        let height = info.text.ga_height(font: 12, width: kTRTCUserWidth-60)
        return 50+height+20
    }
    
    func tableView(_ tableView: NSTableView, shouldSelectRow row: Int) -> Bool {
        let rowView = tableView.rowView(atRow: row, makeIfNecessary: false)
        rowView?.isEmphasized = true
        rowView?.isGroupRowStyle = false
        rowView?.isSelected = false
        rowView?.isFloating = false
        rowView?.isNextRowSelected  = false
        rowView?.isPreviousRowSelected = false
        rowView?.isTargetForDropOperation = false
        return true
    }
    
    func tableViewSelectionDidChange(_ notification: Notification) {
        
    }
}

extension TalkViewController:TalkInputDelegate{
    func talkInput_otherBtnAction(inputView: TalkInputView, senber: ZHButton) {
        let menu = NSMenu.init()
        menu.isDark = true
        self.createItems().forEach { (item) in
            menu.addItem(item)
        }
        menu.needsUpdate()
        self.upMenu = menu
        let p = NSPoint(x: 30, y: -senber.frame.height)
        menu.popUp(positioning: nil, at: p, in: senber)
    }
    
    
    func createItems() -> [NSMenuItem] {
        var item:[NSMenuItem] = []
        let menuNames = ["保存历史记录","打开文件","---","所有人","其他"]
        
        let contents = File.readFileContents(url: File.chatURL.path+"/"+File.contents)
        let filters = contents.filter { (fileName) -> Bool in
            return File.chatFileName==fileName
        }
        for (inx,val) in menuNames.enumerated() {
            let menu = NSMenuItem.init(title: val, action: #selector(touchUpMenuAction(senber:)) , keyEquivalent: "")
            menu.tag = inx
            menu.state = .off
            menu.target = self
            if inx == 1 {
                menu.isHidden = !(filters.count > 0)
            }
            item.append(menu)
        }
        return item
    }
    
    @objc func touchUpMenuAction(senber:NSMenuItem) {
        self.upMenu?.cancelTracking()
        
        switch senber.tag {
        case 0:
            self.saveFile()
        case 1:
            self.openFileTack()
        default:
            break
        }
    }
    
    func openFileTack() {
        XQProcess.openFile(fileName: File.chatFileName, basicPath: File.chatURL.path+"/"+File.contents)
    }
    
    func saveFile() {
        let string = self.modeToString(modes: self.dataList)
        File.createFile(name: File.chatFileName, contents: File.contents, txt: string, fileBaseUrl: File.chatURL)
    }
    
    func modeToString(modes:[ChatData]) -> String {
        var string:String = ""
        for (_,value) in modes.enumerated() {
            let toName = value.toNames.count==0 ? "所有人":value.toNames[0]
            let left = value.formName+" to "+toName
            var space:String = ""
            let count = (50 - left.count)
            for _ in 0..<count {
                space.append(" ")
            }
            let contont = left+space+value.time+"\n    "+value.text+"\n\n"
            string+=contont
        }
        return string
    }
    
    func talkInput_confirmBtnAction(inputView: TalkInputView) {
        var text = inputView.teView.txView.string
        if let index = text.indexDistance(of: "\n")  {
           text = text.substring(toIndex: index)
        }
        if Td.sh().cloud.disBararage == false || String.isHostId() {
            if text != "" {
                let s =  inputView.teView.txView.textStorage?.string
                MTNot.postNotBarrge(text: text)
                IMcmd.shared.barrage(txt: text)
                inputView.teView.txView.string = ""
                
            }
        }else {
            show_msg("主持人已禁止聊天")
        }
        
    }
}

extension TalkViewController {
    @objc func receiveBarrge(not:Notification) {
        self.tabView.kreloadData()
        self.scrollView.scrollToBottom()
    }
}

extension Collection where Element: Equatable {
    func indexDistance(of element: Element) -> Int? {
        guard let index = firstIndex(of: element) else { return nil }
        return distance(from: startIndex, to: index)
    }
}

extension StringProtocol where Index == String.Index {
    func indexDistance(of string: Self) -> Int? {
        guard let index = range(of: string)?.lowerBound else { return nil }
        return distance(from: startIndex, to: index)
    }
}
